package edu.mbb.cloud.nacos.listen;


import java.util.Arrays;
import java.util.List;
import java.util.Properties;


/**
 * nacos监听的核心操作
 */
public class NacosConfigService implements ConfigService {


    private static final long POST_TIMEOUT = 3000L;

    private static final String EMPTY = "";


    /**
     * longpolling
     */
    private ClientWorker worker;
    private String namespace;
    private String encode="UTF-8";
    //此处接口为扩展接口 为了 做拦截功能 提供了对应的接口给用户，根据自己的需要进行对应的过滤和拦截功能。
    //private ConfigFilterChainManager configFilterChainManager = new ConfigFilterChainManager();

    public NacosConfigService(Properties properties) throws RuntimeException {
        //初始化命名空间 可以通过系统变量来改变配置文件中的namespace 我们就不做这个功能了
        initNamespace(properties);
        worker = new ClientWorker(properties);
    }

    private void initNamespace(Properties properties){
        this.namespace=properties.getProperty("namespace");
    }


    @Override
    public String getConfig(String dataId, String group) throws RuntimeException {
        return getConfigInner(namespace, dataId, group);
    }

    @Override
    public void addListener(String dataId, String group, Listener listener) throws Exception {
        String config = getConfig(dataId, group);
        worker.addTenantListenersWithContent(dataId, group, config,Arrays.asList(listener));
    }


    private String getConfigInner(String tenant, String dataId, String group )  {

        // 优先使用本地配置 不适用本地
        String content="";
        try {
            content = worker.getServerConfig(tenant,dataId, group );


            return content;
        } catch (Exception ioe) {
                ioe.printStackTrace();
        }
        return content;
    }



}
